﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MapMgr : MonoBehaviour
{
    private AStarWrapper astar = null;
    private MapNavAgent astarNav = null;
    private Camera camera = null;

    public void initMap() {
        // 初始化寻路工具
        this.astar = new AStarWrapper();
        this.astar.InitWithMapData(Level1_MapData.GoMap, Level1_MapData.Width, 
                                   Level1_MapData.Height, Level1_MapData.Size);

        // end

        // 释放角色
        GameObject rolePrefab = ResMgr.Instance.GetAssetCache<GameObject>("Charactors/role1/role1.prefab");
        GameObject role = GameObject.Instantiate(rolePrefab);
        role.name = rolePrefab.name;

        role.transform.SetParent(this.transform, false);
        Transform spawnPoint = this.transform.Find("SpawnPoint");
        role.transform.position = spawnPoint.position;
        // 导航初始化
        this.astarNav = role.AddComponent<MapNavAgent>();
        this.astarNav.InitMapNavAgent(5.0f);
        // end 

        // 获取摄像机
        this.camera = this.transform.Find("Camera").GetComponent<Camera>();
        // end

        // 释放物品
        // end


    }

    private void onMapTouch() {
        Vector3 src = this.astarNav.transform.position; // 角色的起点;
        Ray ray = this.camera.ScreenPointToRay(Input.mousePosition);

        RaycastHit hitInfo;
        if (Physics.Raycast(ray, out hitInfo)) {
            Vector3 dst = hitInfo.point;

            if (this.astar.AstarSearch(src, dst)) { // 如果寻到了路
                Vector3[] roads = this.astar.GetFilterRoadData();
                this.astarNav.NavOnRoad(roads);
            }
        }
    }

    private void Update() {
        if (Input.GetMouseButtonDown(0)) {
            this.onMapTouch();
        }
    }
}
